package com.xckj.teacher.framework.net

import com.xckj.teacher.ui.App
import com.xckj.teacher.ui.activity.LoginActivity
import com.xckj.teacher.util.ActivityMessenger.startActivityNew
import com.xckj.teacher.util.CacheUtil.clearAll
import com.xckj.teacher.util.CacheUtil.getToken
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * @Author: ChenYao
 * @Describe: 头部拦截器
 * @Date: 2024/4/10 23:08
 */
class HeadIntercept : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val builder = oldRequest.newBuilder()
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
            .addHeader("Accept", "*/*")
        if (getToken().isNotEmpty()) {
            builder.addHeader("token", getToken())
        }
        val proceed = chain.proceed(builder.build())
        if (proceed.code() == 401) {
            clearAll()
            startActivityNew(App.instance.baseContext, LoginActivity::class)
        }
        return proceed
    }
}